package net.jgrm.idgenerator.config;

import lombok.extern.slf4j.Slf4j;
import net.jgrm.idgenerator.service.IdGenerator;
import net.jgrm.idgenerator.service.impl.RedisIdGenerator;
import net.jgrm.idgenerator.service.impl.SnowflakeIdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * ID生成器自动配置类
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(IdGeneratorProperties.class)
public class IdGeneratorAutoConfiguration {


    /**
     * 雪花算法ID生成器 Bean
     */
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnExpression("'${id.generator.type}'.equalsIgnoreCase('snowflake')")
    public IdGenerator snowflakeIdGenerator() {
        SnowflakeIdGenerator generator = new SnowflakeIdGenerator();
        log.info("初始化雪花算法ID生成器");
        return generator;
    }

    /**
     * Redis自增ID生成器 Bean
     */
    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnExpression("'${id.generator.type}'.equalsIgnoreCase('redis')")
    @ConditionalOnClass(RedisTemplate.class)
    public IdGenerator redisIdGenerator(@Autowired RedisTemplate<String, Object> redisTemplate) {
        RedisIdGenerator generator = new RedisIdGenerator(redisTemplate);
        log.info("初始化Redis自增ID生成器");
        return generator;
    }
}